package com.jieli.bt.att.util;

import android.text.TextUtils;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Locale;

/**
 * 格式化工具类
 *
 * Created by zqjasonzhong on 2018/08/06
 */

public class CHexConver {
    private final static String sHexStr = "0123456789ABCDEF";
    private final static char[] sHexChars = sHexStr.toCharArray();
    private static final int ADDRESS_LENGTH = 17;

    /**
     * 检查16进制字符串是否有效
     *
     * @param sHex String 16进制字符串
     * @return boolean
     */
    public static boolean checkHexStr(String sHex) {
        if (sHex == null || sHex.isEmpty()) return false;
        String temp = sHex.trim().replaceAll("\\s*|\\r|\\n|\\t", "").toUpperCase(Locale.US);
        int iLen = temp.length();
        if (iLen > 1 && iLen % 2 == 0) {
            for (int i = 0; i < iLen; i++)
                if (!sHexStr.contains(temp.substring(i, i + 1)))
                    return false;
            return true;
        } else
            return false;
    }

    /**
     * 十六进制字符串转换成 ASCII字符串
     *
     * @param hexStr String Byte字符串
     * @return String 对应的字符串
     */
    public static String hexStr2ASCII(String hexStr) {
        if (hexStr == null) return null;
        hexStr = hexStr.trim().replaceAll("\\s*|\\r|\\n|\\t", "").toUpperCase(Locale.US);
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int iTmp;
        for (int i = 0; i < bytes.length; i++) {
            iTmp = sHexStr.indexOf(hexs[2 * i]) << 4;
            iTmp |= sHexStr.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (iTmp & 0xFF);
        }
        String result = "";
        try {
            result = new String(bytes, "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * bytes字符串转换为Byte值
     *
     * @param hexStr String Byte字符串，每个Byte之间没有分隔符(字符范围:0-9 A-F)
     * @return byte[]
     */
    public static byte[] hexStr2Bytes(String hexStr) {
        if (hexStr == null) return null;
        /*对输入值进行规范化整理*/
        hexStr = hexStr.trim().replaceAll("\\s*|\\r|\\n|\\t", "").toUpperCase(Locale.US);
        //处理值初始化
        int m, n;
        int len = hexStr.length() / 2; //计算长度
        byte[] ret = new byte[len]; //分配存储空间

        for (int i = 0; i < len; i++) {
            m = i * 2 + 1;
            n = m + 1;
            ret[i] = (byte) (Integer.decode("0x" + hexStr.substring(i * 2, m) + hexStr.substring(m, n)) & 0xFF);
        }
        return ret;
    }

    /**
     * bytes转换成十六进制字符串
     *
     * @param data byte[] byte数组
     * @param len  int 取前N位处理 N=iLen
     * @return String 每个Byte值之间空格分隔
     */
    public static String byte2HexStr(byte[] data, int len) {
        if (data == null) return "";
        len = Math.min(data.length, len);
        StringBuilder sb = new StringBuilder();
        for (int n = 0; n < len; n++) {
            sb.append(sHexChars[(data[n] & 0xFF) >> 4]);
            sb.append(sHexChars[data[n] & 0x0F]);
            if (n == len - 1) continue;
            sb.append(" ");
        }
        return sb.toString().trim().toUpperCase(Locale.US);
    }

    /**
     * bytes转换成十六进制字符串
     *
     * @param data byte[] byte数组
     * @return String 每个Byte值之间空格分隔
     */
    public static String byte2HexStr(byte[] data) {
        if (data == null || data.length == 0) return "";
        return byte2HexStr(data, data.length);
    }

    /**
     * 字符串转换成十六进制字符串
     *
     * @param str String 待转换的ASCII字符串
     * @return String 每个Byte之间空格分隔，如: [61 6C 6B]
     */
    public static String str2HexStr(String str) {
        if (str == null) return null;
        byte[] bs = null;
        try {
            bs = str.getBytes("GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (bs == null || bs.length == 0) {
            return "";
        }
        return byte2HexStr(bs);
    }

    /**
     * 十六进制数组转成ASCII字符串
     *
     * @param data byte[] 十六进制数组
     * @return String ASCII字符串
     */
    public static String bytesToStr(byte[] data) {
        if (data == null) return "";
        return hexStr2ASCII(byte2HexStr(data));
    }

    /**
     * int转成十六进制字符串
     *
     * @param num 整型数字
     * @return String 16进制字符串
     */
    public static String int2HexStr(int num, int len) {
        if (len == 2) {
            return String.format(Locale.ENGLISH, "%02x", num);
        }
        return byte2HexStr(intToBigBytes(num));
    }


    /**
     * String的字符串转换成unicode的String
     *
     * @param strText String 全角字符串
     * @return String 每个unicode之间无分隔符
     */
    public static String strToUnicode(String strText) {
        if (strText == null) return null;
        char c;
        StringBuilder str = new StringBuilder();
        int intAsc;
        String strHex;
        for (int i = 0; i < strText.length(); i++) {
            c = strText.charAt(i);
            intAsc = c;
            strHex = Integer.toHexString(intAsc);
            if (intAsc > 128)
                str.append("\\u");
            else // 低位在前面补00
                str.append("\\u00");
            str.append(strHex);
        }
        return str.toString();
    }

    /**
     * unicode的String转换成String的字符串
     *
     * @param hex String 16进制值字符串 （一个unicode为2byte）
     * @return String 全角字符串
     */
    public static String unicodeToString(String hex) {
        if (hex == null) return null;
        int t = hex.length() / 6;
        int iTmp = 0;
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < t; i++) {
            String s = hex.substring(i * 6, (i + 1) * 6);
            // 将16进制的string转为int
            iTmp = (Integer.valueOf(s.substring(2, 4), 16) << 8) | Integer.valueOf(s.substring(4), 16);
            // 将int转换为字符
            str.append(new String(Character.toChars(iTmp)));
        }
        return str.toString();
    }

    /**
     * Int 转 16进制字符串
     *
     * @param num 整型数字
     * @return 16进制字符串
     */
    public static String intToHexString(int num) {
        return String.format(Locale.ENGLISH, "%02x", num);
    }

    /**
     * Int 转 Byte
     *
     * @param num 整型
     * @return Byte
     */
    public static byte intToByte(int num) {
        return (byte) num;
    }

    /**
     * Byte 转 整型
     *
     * @param b 字节
     * @return 整型
     */
    public static int byteToInt(byte b) {
        return b & 0xFF;
    }

    /**
     * Byte 转 Hex
     */
    public static String byteToHexString(byte b) {
        return intToHexString(b & 0xFF);
    }


    /**
     * int 转码 Byte数据(小端存储， 4字节)
     *
     * @param n int数据
     * @return 生成的byte数组
     */
    public static byte[] intToLittleBytes(int n) {
        byte[] b = new byte[4];
        b[0] = (byte) (n & 0xff);
        b[1] = (byte) (n >> 8 & 0xff);
        b[2] = (byte) (n >> 16 & 0xff);
        b[3] = (byte) (n >> 24 & 0xff);
        return b;
    }

    /**
     * int 转码 Byte数据(小端存储， 2字节)
     *
     * @param num int数据
     * @return 生成的byte数组
     */
    public static byte[] intToLittleBytes2(int num) {
        byte[] buf = new byte[2];
        buf[0] = (byte) (num & 0xff);// 最低位
        buf[1] = (byte) ((num >> 8) & 0xff); // 次低位
        return buf;
    }

    /**
     * int 转码 Byte数据(大端存储， 4字节)
     *
     * @param n int数据
     * @return 生成的byte数组
     */
    public static byte[] intToBigBytes(int n) {
        byte[] b = new byte[4];
        b[3] = (byte) (n & 0xff);
        b[2] = (byte) (n >> 8 & 0xff);
        b[1] = (byte) (n >> 16 & 0xff);
        b[0] = (byte) (n >> 24 & 0xff);
        return b;
    }

    /**
     * int 转码 Byte数据(大端存储， 2字节)
     *
     * @param num int数据
     * @return 生成的byte数组
     */
    public static byte[] int2byte2(int num) {
        byte[] buf = new byte[2];
        buf[1] = (byte) (num & 0xff);// 最低位
        buf[0] = (byte) ((num >> 8) & 0xff);// 次低位
        return buf;
    }

    /**
     * 将byte类型的数据转换为int数组
     *
     * @param h 高位
     * @return l 低位
     */
    public static int bytesToInt(byte h, byte l) {
        int result = (0xff & h) << 8;
        result = result + (0xff & l);
        return result;
    }

    /**
     * 将byte类型的数据转换为int数组
     */
    public static int bytesToInt(byte[] value) {
        if (value == null || value.length < 4) return 0;
        return (((value[0] & 0xFF) << 24)
                | ((value[1] & 0xFF) << 16)
                | ((value[2] & 0xFF) << 8)
                | (value[3] & 0xFF));
    }

    /**
     * 将byte类型的数据转换为int数组
     *
     * @param data
     */
    public static int bytesToInt(byte[] data, int start, int len) {
        if (null == data || start + len > data.length) return -1;
        switch (len) {
            case 1:
                return byteToInt(data[start]);
            case 2:
                return bytesToInt(data[start], data[start + 1]);
            default:
                byte[] buf = new byte[4];
                System.arraycopy(data, start, buf, 0, len);
                return bytesToInt(buf);
        }
    }

    public static int bytesLittleToInt(byte[] data) {
        if (data == null || data.length < 4) return 0;
        return (((data[3] & 0xFF) << 24)
                | ((data[2] & 0xFF) << 16)
                | ((data[1] & 0xFF) << 8)
                | (data[0] & 0xFF));
    }

    /**
     * 将byte类型的数据转换为int数组
     * 数据格式：小端端
     *
     * @param data
     */
    public static int bytesLittleToInt(byte[] data, int start, int len) {
        if (null == data || start + len > data.length) return -1;
        switch (len) {
            case 1:
                return byteToInt(data[start]);
            case 2:
                return bytesToInt(data[start + 1], data[start]);
            default:
                byte[] buf = new byte[4];
                System.arraycopy(data, start, buf, 0, len);
                return bytesLittleToInt(buf);
        }
    }

    /**
     * 将byte转换为一个长度为8的byte数组，数组每个值代表bit
     */
    public static byte[] getBooleanArray(byte b) {
        byte[] array = new byte[8];
        for (int i = 7; i >= 0; i--) {
            array[i] = (byte) (b & 1);
            b = (byte) (b >> 1);
        }
        return array;
    }

    /**
     * 将byte转换为一个长度为8的byte数组，数组每个值代表bit
     * (大端处理)
     */
    public static byte[] getBooleanArrayBig(byte b) {
        byte[] array = new byte[8];
        for (int i = 0; i < 8; i++) {
            array[i] = (byte) (b & 1);
            b = (byte) (b >> 1);
        }
        return array;
    }

    /**
     * 将byte类型的数据转换为int数组
     *
     * @param h 高位
     * @return l 低位
     */
    public static short bytesToShort(byte h, byte l) {
        return (short) bytesToInt(h, l);
    }

    public static short bytesToShort(byte[] data, int start) {
        return (short) bytesToInt(data, start, 2);
    }


    /**
     * short
     * 原理：将short数据中的四个byte取出，分别存储
     *
     * @param n short数据
     * @return 生成的byte数组
     */
    public static byte[] shortToBytes(short n) {
        return intToLittleBytes2(n);
    }

    /**
     * short
     * 原理：将short数据中的2个byte取出，分别存储
     *
     * @param n short数据
     * @return 生成的byte数组
     */
    public static byte[] shortToBigBytes(short n) {
        return int2byte2(n);
    }

    /**
     * Byte数据 转码 long
     *
     * @param data     byte[] 数据
     * @param isLittle boolean 是否小端存储
     * @return long 长整形
     */
    public static long bytesToLong(byte[] data, boolean isLittle) {
        if (null == data || data.length < 8) return -1;
        ByteBuffer byteBuffer = ByteBuffer.wrap(data);
        byteBuffer.order(isLittle ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
        return byteBuffer.getLong();
    }

    /**
     * Byte数据 转码 long（大端存储）
     *
     * @param data byte[] 数据
     * @return long 长整形
     */
    public static long bytesToLong(byte[] data) {
        return bytesToLong(data, false);
    }

    /**
     * 将byte类型的数据转换为long
     *
     * @param data
     */
    public static long bytesToLong(byte[] data, int start, int len) {
        if (null == data || len < 8 || start + len > data.length) return -1;
        byte[] buf = new byte[8];
        System.arraycopy(data, start, buf, 0, buf.length);
        return bytesToLong(buf);
    }

    /**
     * 把byte转为字符串的bit
     */
    public static String byteToBit(byte b) {
        return ""
                + (byte) ((b >> 7) & 0x1) + (byte) ((b >> 6) & 0x1)
                + (byte) ((b >> 5) & 0x1) + (byte) ((b >> 4) & 0x1)
                + (byte) ((b >> 3) & 0x1) + (byte) ((b >> 2) & 0x1)
                + (byte) ((b >> 1) & 0x1) + (byte) ((b) & 0x1);
    }

    /**
     * 二进制字符串转byte
     */
    public static byte decodeBinaryString(String byteStr) {
        int re, len;
        if (null == byteStr) {
            return 0;
        }
        len = byteStr.length();
        if (len != 4 && len != 8) {
            return 0;
        }
        if (len == 8) {// 8 bit处理
            if (byteStr.charAt(0) == '0') {// 正数
                re = Integer.parseInt(byteStr, 2);
            } else {// 负数
                re = Integer.parseInt(byteStr, 2) - 256;
            }
        } else {// 4 bit处理
            re = Integer.parseInt(byteStr, 2);
        }
        return (byte) re;
    }

    /**
     * 16进制数据包转换成地址格式
     *
     * @param data 16进制数据包
     * @return 蓝牙地址
     */
    public static String hexDataCovetToAddress(byte[] data) {
        StringBuilder sb = new StringBuilder();
        if (data != null && data.length == 6) {
            for (int n = 0; n < data.length; n++) {
                sb.append(sHexChars[(data[n] & 0xFF) >> 4]);
                sb.append(sHexChars[data[n] & 0x0F]);
                if (n != (data.length - 1)) {
                    sb.append(":");
                }
            }
        }
        return sb.toString();
    }

    /**
     * 检查地址是否有效的蓝牙地址
     *
     * @param address String 地址
     * @return boolean 结果
     */
    public static boolean checkBluetoothAddress(String address) {
        if (address == null || address.length() != ADDRESS_LENGTH) {
            return false;
        }
        for (int i = 0; i < ADDRESS_LENGTH; i++) {
            char c = address.charAt(i);
            switch (i % 3) {
                case 0:
                case 1:
                    if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) {
                        // hex character, OK
                        break;
                    }
                    return false;
                case 2:
                    if (c == ':') {
                        break; // OK
                    }
                    return false;
            }
        }
        return true;
    }

    /**
     * 蓝牙地址转换成16进制数据包
     *
     * @param address 蓝牙地址
     * @return 16进制数据包
     */
    public static byte[] addressCovertToByteArray(String address) {
        if (!checkBluetoothAddress(address)) return new byte[0];
        String hexString = address.replace(":", "");
        byte[] addrBuf = new byte[hexString.length() / 2];
        if (addrBuf.length != 6) { //地址符合规范
            return new byte[0];
        }
        for (int i = 0; i < addrBuf.length; i++) {
            int index = i * 2;
            if (index + 2 <= hexString.length()) {
                try {
                    int value = Integer.valueOf(hexString.substring(index, index + 2), 16);
                    addrBuf[i] = (byte) value;
                } catch (Exception e) {
                    e.printStackTrace();
                    return new byte[0];
                }
            }
        }
        return addrBuf;
    }

    /**
     * 编码16进制字符转成byte
     *
     * @param hChar 高位16进制字符
     * @param lChar 低位16进制字符
     * @return byte值
     */
    public static byte decodeHexChar(char hChar, char lChar) {
        String hString = hexChar2BinaryString(hChar);
        String lString = hexChar2BinaryString(lChar);
        String result = "";
        if (!TextUtils.isEmpty(hString)) {
            result = hString;
        }
        if (!TextUtils.isEmpty(lString)) {
            result += lString;
        }
        if (TextUtils.isEmpty(result)) {
            return (byte) 0;
        } else {
            return decodeBinaryString(result);
        }
    }

    /**
     * 获取指定位置的bit值
     *
     * @param src 原始数据
     * @param pos 位置
     */
    public static int getBitByPosition(int src, int pos) {
        if (pos >= 0 && pos < 32) {
            return ((src >> pos) & 0x1);
        }
        return 0;
    }

    /**
     * 查询字节位的数值是否为1
     *
     * @param value 字节
     * @param bit   字节位
     * @return 结果
     */
    public static boolean checkBitValue(byte value, int bit) {
        return ((value >> bit) & 0x01) == 0x01;
    }

    /**
     * 设置Bit位的值
     *
     * @param value  字节
     * @param bit    字节位
     * @param result 结果
     * @return 改变后的字节
     */
    public static byte setBitValue(byte value, int bit, boolean result) {
        if (result) return (byte) (value | (0x01 << bit));
        return (byte) (value & ~(0x01 << bit));
    }

    private static String hexChar2BinaryString(char src) {
        String result = "";
        if (src == '0') {
            result = "0000";
        } else if (src == '1') {
            result = "0001";
        } else if (src == '2') {
            result = "0010";
        } else if (src == '3') {
            result = "0011";
        } else if (src == '4') {
            result = "0100";
        } else if (src == '5') {
            result = "0101";
        } else if (src == '6') {
            result = "0110";
        } else if (src == '7') {
            result = "0111";
        } else if (src == '8') {
            result = "1000";
        } else if (src == '9') {
            result = "1001";
        } else if (src == 'A' || src == 'a') {
            result = "1010";
        } else if (src == 'B' || src == 'b') {
            result = "1011";
        } else if (src == 'C' || src == 'c') {
            result = "1100";
        } else if (src == 'D' || src == 'd') {
            result = "1101";
        } else if (src == 'E' || src == 'e') {
            result = "1110";
        } else if (src == 'F' || src == 'f') {
            result = "1111";
        }
        return result;
    }

}